package com.ycsj.goldmedalnewconcept.teacher.activity;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.base.BaseApplication;
import com.ycsj.common.base.BusInfo;
import com.ycsj.common.base.OnloadingMoreListener;
import com.ycsj.common.manager.BqaManager;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.SrfManager;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.Constants;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.adapter.EventAdapter;
import com.ycsj.goldmedalnewconcept.common.bean.EventInfo;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.EventUtils;
import com.ycsj.goldmedalnewconcept.teacher.adapter.ClassGvAdapter;
import com.ycsj.goldmedalnewconcept.teacher.bean.ClassInfo;
import com.ycsj.goldmedalnewconcept.teacher.utils.ClassPoputil;
import com.ycsj.goldmedalnewconcept.teacher.utils.ClassUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * 活动列表
 * Created by Administrator on 2019/4/1 0001.
 */

public class TeacherEventListActivity extends BaseActivity implements SrfManager.OnPullRefreshListener, OnloadingMoreListener {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.lv_edit)
    ImageView lvEdit;
    @BindView(R.id.lv_class)
    ImageView lvClass;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.srf)
    SmartRefreshLayout srf;
    @BindView(R.id.rl_loading)
    RelativeLayout rlLoading;

    //所有班级的列表
    private List<ClassInfo.ListBean> classInfos;

    //展示班级列表的适配器
    private ClassGvAdapter classGvAdapter;

    //记录弹出展示班级列表PopUpWindow的选中位置的值,默认第一个被选中
    private int popSelectedPos = 0;

    //数据适配器
    private EventAdapter adapter;

    //数据集合
    private List<EventInfo.ListBean> oldDatas;

    //空视图
    private View emptyView;

    //页面更新的标识
    public static final int UPDATE = 0x532;

    @Override
    protected int getContentLayout() {
        return R.layout.activity_event_list;
    }

    @Override
    protected void init() {

        //初始化状态栏
        initStateBar();

        //初始化下拉刷新
        initSrf();

        //初始化状态
        initState();

        //请求班级数据
        httpClass();

    }


    /**
     * 请求班级里列表数据
     */
    private void httpClass() {
        ClassUtil.httpClass(rlLoading, this, new ClassUtil.onSuccessListener() {
            @Override
            public void onSuccess(List<ClassInfo.ListBean> datas) {
                //回调班级数据
                classInfos = datas;

                //证明有班级
                lvEdit.setVisibility(View.VISIBLE);
                lvClass.setVisibility(View.VISIBLE);

                //设置数据
                initRv();

                //请求页面列表数据
                httpPageData(popSelectedPos, BqaManager.NORML);
            }

            @Override
            public void hasNoData() {
                //没有班级,不显示顶部的切换班级的按钮和
                lvEdit.setVisibility(View.INVISIBLE);
                lvClass.setVisibility(View.INVISIBLE);
            }
        });
    }


    /**
     * 请求页面数据
     *
     * @param popSelectedPos
     * @param method
     */
    private void httpPageData(int popSelectedPos, int method) {

        EventUtils.httpEvent(this, method, classInfos.get(popSelectedPos).getNum() + "", "", new EventUtils.OnRequestListener() {

            @Override
            public void onSuccess(int method, List<EventInfo.ListBean> newDatas) {
                if (method == BqaManager.NORML) {
                    if (rlLoading != null && rlLoading.getVisibility() == View.VISIBLE) {
                        rlLoading.setVisibility(View.GONE);
                    }
                    if (srf != null && srf.getVisibility() != View.VISIBLE) {
                        srf.setVisibility(View.VISIBLE);
                    }
                    oldDatas.clear();
                    oldDatas.addAll(newDatas);
                    BqaManager.setRv(emptyView, TeacherEventListActivity.this, adapter, rv, TeacherEventListActivity.this);
                } else {
                    //更新数据
                    BqaManager.updateRvBySmf(method, srf, rv, oldDatas, newDatas, adapter);
                }
            }

            @Override
            public void onStateError(int method) {
                if (method == BqaManager.NORML) {
                    if (rlLoading != null && rlLoading.getVisibility() == View.VISIBLE) {
                        rlLoading.setVisibility(View.GONE);
                    }
                } else if (method == BqaManager.PULLREFRESH) {
                    //下拉刷新的时候关闭下拉刷新
                    if (srf != null) {
                        srf.finishRefresh(false);
                    }
                } else if (method == BqaManager.LOADINDGMORE) {
                    //加载更多的时候关闭加载更多
                    adapter.loadMoreComplete();
                }
            }

            @Override
            public void onError(int method) {
                BqaManager.setErrorNet(rlLoading, srf, method, adapter);
            }
        });


    }

    /**
     * 初始化状态
     */
    private void initState() {
        rlLoading.setVisibility(View.VISIBLE);
        lvClass.setVisibility(View.INVISIBLE);
        lvEdit.setVisibility(View.INVISIBLE);
    }


    /**
     * 初始化下拉刷新
     */
    private void initSrf() {
        SrfManager.setSmartByPullListener(srf, this);
    }


    /**
     * 设置列表数据
     */
    private void initRv() {
        oldDatas = new ArrayList<>();
        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view, null);
        TextView tvMessage = emptyView.findViewById(R.id.tv_content);
        tvMessage.setText("您还未发布活动");
        adapter = new EventAdapter(this, R.layout.parent_rv_event, oldDatas);

        //条目长按事件
//        adapter.setOnItemLongClickListener(new BaseQuickAdapter.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
//
//                if ("2".equals(oldDatas.get(position).getStatus())) {
//                    //已结束的活动长按删除
//                    AlertDialogUtil.showAlertDialog(true, TeacherEventListActivity.this, "确定删除该条活动吗?", new AlertDialogUtil.onListener() {
//                        @Override
//                        public void onClickOk() {
//                            //删除活动
//                            doDeletEvent(position);
//                        }
//
//                        @Override
//                        public void onClickDismiss() {
//
//                        }
//                    });
//                }
//                return false;
//            }
//        });

        //条目点击事件
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //整体条目的点击事件
                // 跳转到活动详情界面
                Intent intent = new Intent(TeacherEventListActivity.this, TeacherEventDetailsActivity.class);
                intent.putExtra("data", oldDatas.get(position));
                startActivity(intent);
            }
        });
    }


    /**
     * 删除已结束的活动的方法
     */
    private void doDeletEvent(final int position) {
        CustomDialogManager.show(this, "删除中...");
        //删除的操作
        Map<String, String> map = new HashMap<>();

        map.put("type", "12");

        map.put("acc", AccountUtils.getAccount(BaseApplication.context));

        map.put("role", AccountUtils.getRole(BaseApplication.context));

        map.put("rowid", oldDatas.get(position).getRowId() + "");

        HttpUtils.post(HttpAddress.DELETEEVENT, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                ToastUtils.showShort("服务器异常,上传失败");
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                if (!android.text.TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }
                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //删除该条记录,刷新界面
                            oldDatas.remove(position);
                            adapter.notifyItemRemoved(position);
                            //返回成功
                            ToastUtils.showShort("删除成功");
                        } else {
                            ToastUtils.showShort("删除失败,返回异常码是:" + info.getState());
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });
    }

    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_back, R.id.lv_edit, R.id.lv_class})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                //返回
                finish();
                break;
            case R.id.lv_edit:
                //发布活动
                TeacherSendEventActivity.goActivity(this, GsonUtil.listToJson(classInfos));
                break;
            case R.id.lv_class:
                showClassPop();
                break;
        }
    }

    /**
     * 选择班级的弹框
     */
    private void showClassPop() {
        ClassPoputil.showClassPop(this, classInfos, popSelectedPos, llTitle, new ClassPoputil.onPopItemClickListener() {
            @Override
            public void onItemClick(int pos) {
                //记录当前点击条目的位置
                popSelectedPos = pos;

                //请求页面数据
                httpPageData(popSelectedPos, BqaManager.NORML);
            }
        });
    }

    /**
     * 初始化下拉刷新
     *
     * @param refreshlayout
     */
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        httpPageData(popSelectedPos, BqaManager.PULLREFRESH);
    }

    @Override
    public void onLoadMore() {
        httpPageData(popSelectedPos, BqaManager.LOADINDGMORE);
    }


    @Override
    public void busEvent(BusInfo busInfo) {
        if (null != busInfo && UPDATE == busInfo.type) {
            httpPageData(popSelectedPos, BqaManager.PULLREFRESH);
        }
    }
}
